let _getData = {};

function Get(api,param){
    _getData = {api,param:JSON.stringify(param),method:"GET"}
    return $.get(api,param)
}
function Post(api,param){
    _getData = {api,param:JSON.stringify(param),method:"POST"}
    return $.post(api,param)
}

function PostBody(api,param){
    return new Promise(function(ok,err){
        _getData = {api,param:JSON.stringify(param),method:"POST-JSON"}
        $.ajax({ 
              type:"POST",
              url:api,
              dataType:"json",
              contentType:"application/json",             
              data:JSON.stringify(param),
              success:ok,
              error:err
        }); 
   })
}

async function PostError(api,param){
    try{
        const d = await Post(api,param);
        return d;
    }catch(e){
        return {e}
    }
}

 function contains(target,...ps){
    for(let p of ps){
        if(target.indexOf(p) === -1)
            return false;
    }
    return true;
}


function logCreate(id,title){
    return (opt) => {
        const {state,result,api,param,method} = opt;
        $("body").append(`<div class="state-${state}">  
        <ul> 
            <li>${id}:${title}</li> 
            <li>接口:${method} => ${api}</li>
            <li>参数:${param}</li>
            <li>结果:${result} (${state?'通过':'失败'})</li>
        </ul>
        </div>`);
    }
}

/**
 * 测试实体容器
 * key:number,
 * value:void => Promise<void>
 */
const testEntityContainer = {};

function doTest(id,opt){
    /**
     * req ： void => Promise<any>
     * 
     */
    const {title,req,assert} = opt;
    testEntityContainer[id] = async function(){
        const write = logCreate(id,title)
        const pReq = req();
        const _reqInfo = {..._getData};
        try{
            const result = await pReq;
            const state = assert(result);
            write({..._reqInfo,result:JSON.stringify(result),state
            })
        }catch(result){
            write({..._reqInfo,result:JSON.stringify(result),state:false
            })
        }
    }
}

/**
 * 测试全部
 * 
 */
async function  testAll(targetId){

    if(targetId){
        await testEntityContainer[targetId]();
        return;
    }

    for(const p in testEntityContainer){
        await testEntityContainer[p]();
    }
}